package cn.thornbird.orgsync.constraints;

import cn.thornbird.orgsync.util.ReflectUtil;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

@Slf4j
public class FieldsValueMatchValidator implements ConstraintValidator<FieldsValueMatch, Object> {

    private String firstFieldName;

    private String secondFieldName;

    @Override
    public void initialize(FieldsValueMatch fieldsValueMatch) {
        this.firstFieldName = fieldsValueMatch.first();
        this.secondFieldName = fieldsValueMatch.second();
    }

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext context) {
        Object firstValue = ReflectUtil.getValue(object, firstFieldName);
        Object secondValue = ReflectUtil.getValue(object, secondFieldName);
        return Objects.equals(firstValue, secondValue);
    }

}
